package com.dokimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.dokimall.auth.feign.MemberFeignService;
import com.dokimall.auth.feign.ThirdPartFeignService;
import com.dokimall.auth.vo.LoginAcct;
import com.dokimall.auth.vo.UserRegistVo;
import com.dokimall.common.constant.AuthServerConstant;
import com.dokimall.common.exception.BizCodeEnume;
import com.dokimall.common.utils.R;
import com.dokimall.common.vo.MemberVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.xml.ws.soap.Addressing;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;


//    @GetMapping("/login.html")
//    public String loginPage(){
//        return "login";
//    }
//
//    @GetMapping("/reg.html")
//    public String regPage(){
//        return "reg";
//    }
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone")String phone){
        //TODO 接口防刷
        String rediscode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(StringUtils.isNotEmpty(rediscode)){
            long l = Long.parseLong(rediscode.split("_")[1]);
            if(System.currentTimeMillis()-l < 60000){
                // 60秒内不能再发
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        int code = new Random().nextInt(9999);
        long timeMillis = System.currentTimeMillis();
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code+"_"+timeMillis,10, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone, code);
        return R.ok();
    }


    // 重定向携带数据，利用session原理，将数据放在session中，只要跳到下一个页面取出这个数据以后，session里面的数据就会删掉；
    // TODO 1、分布式下的session问题
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo userRegistVo , BindingResult result , RedirectAttributes attributes) {// RedirectAttributes 模拟重定向携带数据
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            attributes.addFlashAttribute("error", errors);
            // 校验出错，重定向到注册页
            return "redirect:http://auth.dokimall.com/reg.html";
        }
        // 验证码检测
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhoneNum());
        if (StringUtils.isNotEmpty(s)) {
            String code = s.split("_")[0];
            if (code.equals(userRegistVo.getCode())) {
                // 验证码校验通过，需要删除缓存中的验证码信息
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhoneNum());
                R r = memberFeignService.memberRegist(userRegistVo);
                if (r.getCode() == 0) {
                    // 注册成功
                    return "redirect:http://auth.dokimall.com/login.html";
                } else {
                    // 注册出现异常
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData("msg",new TypeReference<String>() {}));
                    attributes.addFlashAttribute("error", errors);
                    return "redirect:http://auth.dokimall.com/login.html";
                }
            } else {
                // 验证码校验出错，重定向到注册页
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码有误");
                attributes.addFlashAttribute("error", errors);
                return "redirect:http://auth.dokimall.com/reg.html";
            }
        }else{
            // 验证码为空/过期，重定向到注册页
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码有误");
            attributes.addFlashAttribute("error", errors);
            return "redirect:http://auth.dokimall.com/reg.html";
        }

    }
    @GetMapping("/login.html")
    public String login(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        // 用户已经登录，返回首页
        if (attribute!=null){
            return "redirect:http://dokimall.com";
        }
        return "login";
    }

    @PostMapping("/login")
    public String acctLogin(LoginAcct loginAcct , RedirectAttributes attributes, HttpSession session){
        R r = memberFeignService.login(loginAcct);
        if(r.getCode()==0){
            // TODO 登陆成功后的处理
            // 保存到session
            MemberVo data = r.getData("data", new TypeReference<MemberVo>() {
            });
            System.out.println("登录的用户是{}："+data);
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://dokimall.com/";
        }else {
            // 登陆失败，返回登录页并带上失败信息
            Map<String,String> error = new HashMap<>();
            error.put("msg",r.getData("msg",new TypeReference<String>(){}));
            attributes.addFlashAttribute("error",error);
            return "redirect:http://auth.dokimall.com/login.html";
        }
    }
}
